<template>
  <el-card>
    <template #header>所有成员列表（此功能通常用于后台管理）</template>
    <el-table :data="allPersons" v-loading="loading">
      <el-table-column prop="personId" label="成员ID" width="100" />
      <el-table-column prop="name" label="姓名" />
      <!-- 假设后端返回了 familyName -->
      <el-table-column prop="familyName" label="所在家谱" />
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <!-- 点击详情按钮时，调用新的跳转函数 -->
          <el-button size="small" @click="showPersonDetails(scope.row.personId)">详情</el-button>
          <el-button size="small" type="primary" @click="openPersonDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDeletePerson(scope.row.personId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 【移除】不再需要 PersonDetailDrawer 组件 -->

  <!-- 编辑成员的对话框保持不变 -->
  <PersonFormDialog v-if="selectedFamilyId" v-model:visible="personFormVisible" :family-id="selectedFamilyId" :person-data="selectedPersonForEdit" @success="fetchAllPersons" />
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
// 【新增】导入 useRouter 用于页面跳转
import { useRouter } from 'vue-router';
import { getAllPersonsApi, deletePersonApi } from '@/api/person';
import type { Person, PersonFormData } from '@/types/api';
// 【移除】不再需要 PersonDetailDrawer 的导入
import PersonFormDialog from '@/components/PersonFormDialog.vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter(); // 【新增】
const loading = ref(true);
const allPersons = ref<Person[]>([]);

// 【移除】详情抽屉相关的状态不再需要
// const drawerVisible = ref(false);
// const selectedPersonId = ref<number | null>(null);

// 编辑表单相关状态保持不变
const personFormVisible = ref(false);
const selectedPersonForEdit = ref<PersonFormData | null>(null);
const selectedFamilyId = ref<number | null>(null);

const fetchAllPersons = async () => {
  loading.value = true;
  try {
    allPersons.value = await getAllPersonsApi();
  } finally {
    loading.value = false;
  }
};

// showPersonDetails 函数现在负责跳转到新的详情页面
const showPersonDetails = (personId: number) => {
  router.push({ name: 'PersonDetail', params: { id: personId } });
};

const openPersonDialog = (person: Person) => {
  selectedPersonForEdit.value = {
    personId: person.personId,
    familyId: person.familyId,
    name: person.name,
    gender: person.gender || 'M',
    birthDate: person.birthDate,
    deathDate: person.deathDate
  };
  selectedFamilyId.value = person.familyId;
  personFormVisible.value = true;
};

const handleDeletePerson = (personId: number) => {
  ElMessageBox.confirm('确定删除该成员吗？', '警告', { type: 'warning' })
    .then(async () => {
      await deletePersonApi(personId);
      ElMessage.success('删除成功');
      fetchAllPersons();
    });
};

onMounted(fetchAllPersons);
</script>
